﻿using System;
using System.Data.Services.Client;
using System.Linq;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using Coevery.ViewModel;
using Coevery.ViewModel.EntityDataService;
using System.Windows.Controls.Primitives;
using Microsoft.Phone.Shell;

namespace Coevery.PhoneApp
{
    public partial class Index : PhoneApplicationPage
    {
        private bool _showAll;
        private Popup _popup;
        private IndexViewModel _indexViewModel;
        public Index()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.NavigationMode != System.Windows.Navigation.NavigationMode.Back)
            {

                SetApplicationBarIconButtonEnabled(null, null);
                _popup = new Popup { Child = new PopuWait(), IsOpen = true };
                var userName = App.Setting["Username"].ToString();
                var userQuery = (from c in BaseViewModel.Context.Users
                                 where c.UserName == userName
                                 select c) as DataServiceQuery<User>;
                if (userQuery != null)
                {
                    userQuery.BeginExecute(OnUserExecuteCompleted, userQuery);
                }

            }
            base.OnNavigatedTo(e);
        }

        private void OnUserExecuteCompleted(IAsyncResult ar)
        {
            var query = ar.AsyncState as DataServiceQuery<User>;
            var result = query.EndExecute(ar);
            Dispatcher.BeginInvoke(() =>
                                       {
                                           var user = result.First();
                                           App.Setting["UserId"] = user.UserId.ToString();
                                           _indexViewModel = new IndexViewModel();
                                           _indexViewModel.EnableButton += SetApplicationBarIconButtonEnabled;
                                           DataContext = _indexViewModel;
                                           ShowPopup();
                                       });
        }

        private void LeadListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var resource = LeadListBox.SelectedItem as Lead;
            var app = (ListBox)sender;
            if (app.SelectedIndex == -1) 
            {
                return;
            }
            if (resource != null)
            {
                NavigationService.Navigate(new Uri("/LeadDetail.xaml?Lead=" + resource.LeadId, UriKind.Relative));
            }
            app.SelectedIndex = -1;
            
        }

        private void OpportunityListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var resource = OpportunityListBox.SelectedItem as Opportunity;
            var app = (ListBox)sender;
            if (app.SelectedIndex == -1)
            {
                return;
            }
            if (resource != null)
            {
                NavigationService.Navigate(new Uri("/OpportunityDetail.xaml?Opportunity=" + resource.OpportunityId, UriKind.Relative));
            }
            app.SelectedIndex = -1;
        }

        private void QuoteListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) 
        {
            var resource = QuoteListBox.SelectedItem as Quote;
            var app = (ListBox)sender;
            if (app.SelectedIndex == -1)
            {
                return;
            }
            if(resource!=null)
            {
                NavigationService.Navigate(new Uri("/QuoteDetail.xaml?Quote="+resource.QuoteId,UriKind.Relative));
            }
            app.SelectedIndex = -1;
        }

        private void ContractListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) 
        {
            var resource = ContractListBox.SelectedItem as Contract;
            var app = (ListBox)sender;
            if (app.SelectedIndex == -1)
            {
                return;
            }
            if (resource != null) 
            {
                NavigationService.Navigate(new Uri("/ContractDetail.xaml?Contract="+resource.ContractId,UriKind.Relative));
            }
            app.SelectedIndex = -1;
        }

        private void ShowAll_Click(object sender, EventArgs e)
        {
            SetApplicationBarIconButtonEnabled(null, null);
            ((ApplicationBarIconButton)sender).Text = _showAll ? "Show ALl" : "Just Me";
            _showAll = !_showAll;
            _popup.IsOpen = true;
            var userId = Guid.Parse(App.Setting["UserId"].ToString());
            _indexViewModel.LoadData(_showAll, _popup, userId);
        }

        private void Refresh_Click(object sender, EventArgs e)
        {
            SetApplicationBarIconButtonEnabled(null, null);
            _popup.IsOpen = true;
            var userId = Guid.Parse(App.Setting["UserId"].ToString());
            _indexViewModel.LoadData(_showAll, _popup, userId);
        }

        private void ShowPopup()
        {
            SetApplicationBarIconButtonEnabled(null,null);
            var userId = Guid.Parse(App.Setting["UserId"].ToString());
            _indexViewModel.LoadData(_showAll, _popup, userId);
        }

        public void SetApplicationBarIconButtonEnabled(object sender, EventArgs e)
        {
            foreach (ApplicationBarIconButton item in ApplicationBar.Buttons)
            {
                item.IsEnabled = ((bool?)sender) ?? false;
            }
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (_popup.IsOpen == true)
            {
                _popup.IsOpen = false;
            }
        }
    }
}